package queue;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName MyBlockingQueue
 * @Description 手动实现队列
 * @Company inspur
 * @Author Kevin
 * @Date 2020/7/10 15:51
 * @Version 1.0
 */
public class MyQueue<T> {
    private volatile node head;
    private volatile node tail;
    private volatile AtomicInteger size = new AtomicInteger(0);
    private int length;

    public MyQueue(T t) {
        head = create(t);
        tail = head;
        size.incrementAndGet();
    }

    class node<T> {
        public T value;
        public node next;

        public node(T t) {
            this.value = t;
            this.next = null;
        }
    }

    private node create(T t) {
        node root = new node(t);
        root.next = null;
        return root;
    }

    public Boolean put(T t, int capality) {
        if (tail != null && size.get() < capality) {
            node newNode = new node(t);
            tail.next = newNode;
            tail = tail.next;
            newNode = null;
            size.incrementAndGet();
            return Boolean.TRUE;
        } else if (tail == null && head == null) {
            node newNode = new node(t);
            head = newNode;
            tail = newNode;
            size.incrementAndGet();
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    public T get() {
        if (head == null) {
            return null;
        }

        T t = (T)head.value;
        if (head == tail) {
            tail = head = null;
        } else {
            head = head.next;
        }
        size.decrementAndGet();
        return t;
    }

    public int size() {
        return size.get();
    }


}
